
import 'package:get_storage/get_storage.dart';
import 'package:share_fit/app/tools/log_utils.dart';

class StorageHelper {
  static const storageGlobal = "global";
  static const storageList = "storageList";
  static List<dynamic> storagePaths = [];
  static GetStorage storage = GetStorage();
  static GetStorage? _storageGlobal;

  static Future<void> init() async {
    await GetStorage.init();
    await GetStorage.init(storageGlobal);
    _storageGlobal = GetStorage(storageGlobal);
    if (storage.hasData(storageList)) {
      storagePaths = storage.read(storageList);
      if (storagePaths.isNotEmpty) {
        for (var path in storagePaths) {
          if (storageGlobal != path) {
            await GetStorage.init(path);
          }
        }
      }
    }
  }

  static GetStorage getStorage(path) {
    if (!storagePaths.contains(path)) {
      storagePaths.add(path);
      storage.write(storageList, storagePaths);
    }

    return GetStorage(path);
  }

  static bool hasData(key) {
    return _storageGlobal?.hasData(key) == true;
  }

  static dynamic read(key, {defaultValue}) {
    if (_storageGlobal?.hasData(key) == true) {
      return _storageGlobal!.read(key);
    }

    return defaultValue;
  }

  static dynamic save(key, value) {
    _storageGlobal?.write(key, value);
  }

  static void remove(key) {
    if (hasData(key)) {
      _storageGlobal?.remove(key);
    }
  }

  static void erase(address) {
    List<dynamic> removeList = [];
    for (var path in storagePaths) {
      if (path.startsWith(address)) {
        removeList.add(path);
        GetStorage(path).erase();
        logger.d("erase storage $path");
      }
    }

    if (removeList.isNotEmpty) {
      for (var element in removeList) {
        storagePaths.remove(element);
      }
    }
  }
}